package com.wgts.wgts.mvp.view.activity.mycenter;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.ClipboardManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wgts.wgts.R;
import com.wgts.wgts.base.BaseActivity;
import com.wgts.wgts.control.eventbus.EditNikeNameEventBus;
import com.wgts.wgts.control.matisse.GlideEngine;
import com.wgts.wgts.control.oss.FileUtils;
import com.wgts.wgts.control.oss.OssService;
import com.wgts.wgts.control.toast.MoHuToast;
import com.wgts.wgts.dagger.ComponentHolder;
import com.wgts.wgts.dagger.component.DaggerMyCenterMessageActivityComponent;
import com.wgts.wgts.dagger.module.MyCenterMessageActivityModule;
import com.wgts.wgts.mvp.presenter.IMyCenterMessageActivityPresenter;
import com.wgts.wgts.mvp.view.IMyCenterMessageActivityView;
import com.wgts.wgts.mvp.view.activity.setPassWord.SettingPasswordActivity;
import com.wgts.wgts.netmodle.req.EditMyCenterMessageRequest;
import com.wgts.wgts.netmodle.resp.EditMyCenterMessageEntity;
import com.wgts.wgts.tools.AppInfor;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/*
 *
 *
 *   data:2018/9/2811:02
 *
 */
@RuntimePermissions
public class MyCenterMessageActivity extends BaseActivity implements IMyCenterMessageActivityView {


    @BindView(R.id.back_btn_image)
    ImageView backBtnImage;
    @BindView(R.id.back_btn_ly)
    LinearLayout backBtnLy;
    @BindView(R.id.include_title)
    TextView includeTitle;
    @BindView(R.id.include_text)
    TextView includeText;
    @BindView(R.id.include_right_image)
    ImageView includeRightImage;
    @BindView(R.id.include_right_ly)
    LinearLayout includeRightLy;
    @BindView(R.id.my_center_message_head_image)
    CircleImageView myCenterMessageHeadImage;
    @BindView(R.id.my_center_message_head_ly)
    RelativeLayout myCenterMessageHeadLy;
    @BindView(R.id.my_center_message_nike_name_text)
    TextView myCenterMessageNikeNameText;
    @BindView(R.id.my_center_message_nike_name_ly)
    RelativeLayout myCenterMessageNikeNameLy;
    @BindView(R.id.my_center_message_invitation_code_text)
    TextView myCenterMessageInvitationCodeText;
    @BindView(R.id.invitation_code_copy)
    TextView invitationCodeCopy;
    @BindView(R.id.my_center_message_store_invitation_code_ly)
    RelativeLayout myCenterMessageStoreInvitationCodeLy;
    @BindView(R.id.my_center_message_phone_text)
    TextView myCenterMessagePhoneText;
    @BindView(R.id.phone_change_bind)
    TextView phoneChangeBind;
    @BindView(R.id.my_center_message_phone_ly)
    RelativeLayout myCenterMessagePhoneLy;
    @BindView(R.id.my_center_message_cursh_text)
    TextView myCenterMessageCurshText;
    @BindView(R.id.my_center_message_cursh_password_ly)
    RelativeLayout myCenterMessageCurshPasswordLy;
    private int REQUEST_CODE_CHOOSE = 1;
    private int REQUEST_CHANGE_NIKE_NAME = 2;
    private int MyCenterFragmentResult = 3;
    private int SettingPasswordResult = 4;

    private List<Uri> mSelected;
    private static final String FILE_PATH = "com.wgts.wgts.fileprovider";

    private EditMyCenterMessageRequest request;
    private String headImage, wChartName;

    @Inject
    IMyCenterMessageActivityPresenter presenter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_center_message_activity);
        ButterKnife.bind(this);
        includeTitle.setText("个人资料");
        initView();
    }

    @Override
    public void init() {
        DaggerMyCenterMessageActivityComponent
                .builder()
                .appComponent(ComponentHolder.getInstance().getAppComponent())
                .myCenterMessageActivityModule(new MyCenterMessageActivityModule(this))
                .build()
                .inject(this);
    }

    private void initView() {
        if (AppInfor.getInstance().getUserPhone() != null && !AppInfor.getInstance().getUserPhone().equals("")) {
            if (AppInfor.getInstance().getUserState() < 1) {
                myCenterMessageStoreInvitationCodeLy.setVisibility(View.GONE);
                myCenterMessageCurshPasswordLy.setVisibility(View.GONE);
            } else {
                myCenterMessageStoreInvitationCodeLy.setVisibility(View.VISIBLE);
                myCenterMessageInvitationCodeText.setText(AppInfor.getInstance().getInviteCode());
                myCenterMessageCurshPasswordLy.setVisibility(View.VISIBLE);
            }
            if (AppInfor.getInstance().isModifyPayPassword()) {
                myCenterMessageCurshText.setText("修改支付密码");
            } else {
                myCenterMessageCurshText.setText("去设置");
            }
            //MoHuGlide.getInstance().glideImg(this, AppInfor.getInstance().getUserHead(), myCenterMessageHeadImage);
            myCenterMessageNikeNameText.setText(AppInfor.getInstance().getUserName());
            myCenterMessagePhoneText.setText(AppInfor.getInstance().getUserPhone());
        }
    }

    @OnClick({R.id.back_btn_ly, R.id.my_center_message_head_ly, R.id.my_center_message_nike_name_ly,
            R.id.invitation_code_copy, R.id.my_center_message_store_invitation_code_ly,
            R.id.my_center_message_phone_ly, R.id.my_center_message_cursh_password_ly})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn_ly:
                close();
                break;
            case R.id.my_center_message_head_ly:
                //无修改头像
                //updateHead();
                break;
            case R.id.my_center_message_nike_name_ly:
                jumpResult(MyCenterNikeNameActivity.class, REQUEST_CHANGE_NIKE_NAME, AppInfor.getInstance().getUserName());
                break;
            case R.id.invitation_code_copy:
                break;
            case R.id.my_center_message_store_invitation_code_ly:
                copy(myCenterMessageInvitationCodeText);
                break;
            case R.id.my_center_message_phone_ly:
                jump(ChangePhoneActivity.class);
                break;
            case R.id.my_center_message_cursh_password_ly:
                jumpResult(SettingPasswordActivity.class, SettingPasswordResult, "");
                break;
        }
    }

    //复制方法
    private void copy(TextView textView) {
        ClipboardManager cmb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(textView.getText().toString()); //将内容放入粘贴管理器,在别的地方长按选择"粘贴"即可
        Toast.makeText(this, "复制成功", Toast.LENGTH_SHORT).show();
    }

    private void jump(Class<? extends Activity> clz) {
        Intent intent = new Intent(MyCenterMessageActivity.this, clz);
        startActivity(intent);
    }

    private void jumpResult(Class<? extends Activity> cls, Integer requestCode, String name) {
        Intent intent = new Intent(MyCenterMessageActivity.this, cls);
        intent.putExtra("hint", name);
        startActivityForResult(intent, requestCode);
    }


    @Override
    public void onError(int status, String msg) {
        dialogDismiss();
        MoHuToast.showToast(msg);
    }

    @Override
    public void editMyCenterMessageResult(EditMyCenterMessageEntity entity) {
        dialogDismiss();
        //MoHuGlide.getInstance().glideImg(this, entity.userImage, myCenterMessageHeadImage);
        AppInfor.getInstance().setUserHead(entity.userImage);
    }

    private void updateHead() {
        MyCenterMessageActivityPermissionsDispatcher.addIdeaBackImageWithPermissionCheck(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            showDialog();
            mSelected = Matisse.obtainResult(data);
            if (mSelected != null && mSelected.size() > 0) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        OssService.getInstance(MyCenterMessageActivity.this).beginupload("head",
                                FileUtils.getRealFilePath(MyCenterMessageActivity.this, mSelected.get(0)),
                                new OssService.ProgressCallback() {
                                    @Override
                                    public void onProgressCallback(double progress, String url) {
                                        if (progress == 100) {
                                            headImage = url;
                                            if (headImage.equals("")) {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        dialogDismiss();
                                                        MoHuToast.showToast("图片上传失败");
                                                    }
                                                });
                                            } else {
                                                headImage = url;
                                                request = new EditMyCenterMessageRequest();
                                                request.updateType = "UPDATE_USER_IMAGE";
                                                request.userImage = headImage;
                                                presenter.editMyCenterResult(request);
                                            }
                                        }
                                    }
                                });
                    }
                }).start();
            }
        }
        if (requestCode == REQUEST_CHANGE_NIKE_NAME) {
           // MoHuGlide.getInstance().glideImg(this, AppInfor.getInstance().getUserHead(), myCenterMessageHeadImage);
            myCenterMessageNikeNameText.setText(AppInfor.getInstance().getUserName());
            myCenterMessagePhoneText.setText(AppInfor.getInstance().getUserPhone());
            EventBus.getDefault().post(new EditNikeNameEventBus());
        }
        if (requestCode == SettingPasswordResult) {
            if (AppInfor.getInstance().isModifyPayPassword()) {
                myCenterMessageCurshText.setText("修改支付密码");
            } else {
                myCenterMessageCurshText.setText("去设置");
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            close();
        }

        return super.onKeyDown(keyCode, event);
    }

    //返回时的方法
    private void close() {
        Intent intent = new Intent();
        intent.putExtra("result", 1);
        setResult(MyCenterFragmentResult, intent);
        finish();
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
    void addIdeaBackImage() {
        Matisse.from(MyCenterMessageActivity.this)
                .choose(MimeType.ofAll(), false)
                .countable(true)
                .capture(true)
                .captureStrategy(new CaptureStrategy(true, FILE_PATH))
                .maxSelectable(1)
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .imageEngine(new GlideEngine()) // 使用的图片加载引擎
                .forResult(REQUEST_CODE_CHOOSE); // 设置作为标记的请求码
    }

    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
    void addIdeaBackImageWrong() {
        Toast.makeText(MyCenterMessageActivity.this,
                "获取权限失败，可能无法上传照片", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MyCenterMessageActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        initView();
    }
}
